package com.yugao.fintech.draper.security.aspect;

import cn.hutool.core.util.StrUtil;
import com.yugao.fintech.draper.security.annotation.SecurityInner;
import com.yugao.fintech.draper.core.constant.SecurityConstants;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.access.AccessDeniedException;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 内部服务调用是否鉴权切面
 */
@Slf4j
@Aspect
@RequiredArgsConstructor
public class SecurityInnerAspect implements Ordered {

	private final HttpServletRequest request;

	/**
	 * 前置处理Ojbk注解 判断是否为服务内部调用
	 * @param point 连接点
	 * @param securityInner Ojbk注解
	 */
	@SneakyThrows
	@Before("@within(securityInner) || @annotation(securityInner)")
	public void before(JoinPoint point, SecurityInner securityInner) {
		// 实际注入的Ojbk实体由表达式后一个注解决定 即取方法上的注解 若方法上无注解 则获取类上的
		if (securityInner == null) {
			Class<?> clazz = point.getTarget().getClass();
			securityInner = AnnotationUtils.findAnnotation(clazz, SecurityInner.class);
		}

		String header = request.getHeader(SecurityConstants.FROM);
		if (securityInner.inner() && !StrUtil.equals(SecurityConstants.FROM_IN, header)) {
			log.warn("访问接口 {} 没有权限", point.getSignature().getName());
			throw new AccessDeniedException("Access is denied");
		}
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE + 1;
	}

}
